package com.example.chartroom.controller;

import com.example.chartroom.component.OnlineManage;
import com.example.chartroom.mapper.MessageMapper;
import com.example.chartroom.mapper.MessageSessionMapper;
import com.example.chartroom.model.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class WebSocketController extends TextWebSocketHandler {
    @Autowired
    private OnlineManage onlineManage;

    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Autowired
    private MessageMapper messageMapper;
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("连接成功！");
        User user = (User) session.getAttributes().get("user");
        if(user == null) return;
        log.info("{}",user);
        onlineManage.online(user.getUserId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到消息");
        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            log.info("user == null");
            return;
        }
        MessageRequest req = (MessageRequest) objectMapper.readValue(message.getPayload(), MessageRequest.class);
        if(req.getType().equals("message")){
            transferMessage(user, req);
        }else {
            log.info("req.type="+req.getType());
        }
    }

    private void transferMessage(User fromUser, MessageRequest req) throws IOException {
        //设置响应
        MessageResponse res = new MessageResponse();
        res.setSessionId(req.getSessionId());
        res.setContent(req.getContent());
        res.setFromId(fromUser.getUserId());
        res.setFromName(fromUser.getUsername());
        String respJson = objectMapper.writeValueAsString(res);

        //找到该会话的所有用户
        List<Friend> friendList = messageSessionMapper.selectFriendsBySessionId(req.getSessionId(), fromUser.getUserId());
        Friend f = new Friend();
        f.setFriendId(fromUser.getUserId());
        f.setFriendName(fromUser.getUsername());
        friendList.add(f);

        //将消息发送给在线用户
        for(Friend friend : friendList){
            WebSocketSession webSocketSession = onlineManage.getSession(friend.getFriendId());
            if(webSocketSession == null)
                continue;
            webSocketSession.sendMessage(new TextMessage(respJson));
        }

        //将数据存储到数据库
        Message message = new Message();
        message.setFromId(fromUser.getUserId());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());
        messageMapper.add(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("出现异常");
        User user = (User) session.getAttributes().get("user");
        if(user == null) return;
        log.info("{}",user);
        onlineManage.offline(user.getUserId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("连接关闭");
        User user = (User) session.getAttributes().get("user");
        if(user == null) return;
        log.info("{}",user);
        onlineManage.offline(user.getUserId(), session);
    }
}
